﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.Entities;
using MovieRental.SqlRepositoryLibrary.Converters;
using System.Data.SqlClient;
using MovieRental.GeneralDataExceptions;

namespace MovieRental.SqlRepositoryLibrary
{
    public class SqlLoanRepository : SqlRepository<LoanInfo, Guid, LoanConverter>
    {
        public SqlLoanRepository(string connectionString)
            : base(connectionString)
        {
        }

        protected override bool Contains(LoanInfo entity)
        {
            return Contains(entity.EditionId);
        }

        public override void Delete(LoanInfo entity)
        {
            Delete(entity.EditionId);
        }

        public IEnumerable<LoanInfo> LoadAllForCart(Guid cartId)
        {
            using (var connection = ProvideConnection())
            {
                SqlCommand command = Converter.GetReadCommand(cartId);
                command.Connection = connection;
                try
                {
                    SqlDataReader reader = command.ExecuteReader();
                    ICollection<LoanInfo> query = new List<LoanInfo>();
                    while (reader.Read())
                        query.Add(Converter.ConvertFromDataReader(reader));
                    return query;
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Can't connect to the db.", ex);
                }
            }
        }
    }
}
